import json
import webbrowser
import requests
import time
import re
from bs4 import BeautifulSoup
from matplotlib import *
import matplotlib.pyplot as plt
import pandas as pd
from pyecharts import options as opts
from pyecharts.charts import Map

class Position:
    plt.rcParams["font.sans-serif"] = ["SimHei"]
    plt.rcParams["axes.unicode_minus"] = False
    #刘琼徽编写部分
    def paqu_1month_data(self):
        job_list = []
        for pageNum in range(40):
            timestamp = int(time.time())
            key_word = 'python'
            head_url = 'https://we.51job.com/api/job/search-pc?'
            tail_param = "api_key=51job&timestamp=" + str(
                timestamp) + "&keyword=" + key_word + "&searchType=2&function=&industry=&jobArea=000000&jobArea2=&landmark=&metro=&salary=&workYear=&degree=&companyType=&companySize=&jobType=&issueDate=3&sortType=0&pageNum=" + str(
                pageNum) + "&requestId=&pageSize=40&source=1&accountId=&pageCode=sou%7Csou%7Csoulb"
            url = head_url + tail_param
            headers = {'Accept': 'application/json, text/plain, */*', 'Accept-Encoding': 'gzip, deflate, br',
                       'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6', 'Connection': 'keep-alive',
                       'Cookie': 'guid=bed24704cea43240eacb73101cd81594; nsearch=jobarea%3D%26%7C%26ord_field%3D%26%7C%26recentSearch0%3D%26%7C%26recentSearch1%3D%26%7C%26recentSearch2%3D%26%7C%26recentSearch3%3D%26%7C%26recentSearch4%3D%26%7C%26collapse_expansion%3D; slife=lowbrowser%3Dnot%26%7C%26; sensorsdata2015jssdkcross=%7B%22distinct_id%22%3A%22bed24704cea43240eacb73101cd81594%22%2C%22first_id%22%3A%2218ca6691055556-076c28bc39975a4-4c657b58-921600-18ca6691056475%22%2C%22props%22%3A%7B%22%24latest_traffic_source_type%22%3A%22%E7%9B%B4%E6%8E%A5%E6%B5%81%E9%87%8F%22%2C%22%24latest_search_keyword%22%3A%22%E6%9C%AA%E5%8F%96%E5%88%B0%E5%80%BC_%E7%9B%B4%E6%8E%A5%E6%89%93%E5%BC%80%22%2C%22%24latest_referrer%22%3A%22%22%7D%2C%22identities%22%3A%22eyIkaWRlbnRpdHlfY29va2llX2lkIjoiMThjYTY2OTEwNTU1NTYtMDc2YzI4YmMzOTk3NWE0LTRjNjU3YjU4LTkyMTYwMC0xOGNhNjY5MTA1NjQ3NSIsIiRpZGVudGl0eV9sb2dpbl9pZCI6ImJlZDI0NzA0Y2VhNDMyNDBlYWNiNzMxMDFjZDgxNTk0In0%3D%22%2C%22history_login_id%22%3A%7B%22name%22%3A%22%24identity_login_id%22%2C%22value%22%3A%22bed24704cea43240eacb73101cd81594%22%7D%2C%22%24device_id%22%3A%2218ca6691055556-076c28bc39975a4-4c657b58-921600-18ca6691056475%22%7D; NSC_ohjoy-bmjzvo-200-159=ffffffffc3a0d61845525d5f4f58455e445a4a423660; Hm_lvt_1370a11171bd6f2d9b1fe98951541941=1703601278,1703601767,1703646437; Hm_lpvt_1370a11171bd6f2d9b1fe98951541941=1703646437; acw_tc=ac11000117036536732378425e00d8c5547f76fb461e387834fe4a3a773742; acw_sc__v2=658bb12c4d0e3739871334f211fbd70b616fafb0; search=jobarea%7E%60%7C%21recentSearch0%7E%60000000%A1%FB%A1%FA000000%A1%FB%A1%FA0000%A1%FB%A1%FA00%A1%FB%A1%FA99%A1%FB%A1%FA%A1%FB%A1%FA99%A1%FB%A1%FA99%A1%FB%A1%FA99%A1%FB%A1%FA99%A1%FB%A1%FA9%A1%FB%A1%FA99%A1%FB%A1%FA%A1%FB%A1%FA0%A1%FB%A1%FApython%A1%FB%A1%FA2%A1%FB%A1%FA1%7C%21recentSearch1%7E%60000000%A1%FB%A1%FA000000%A1%FB%A1%FA0000%A1%FB%A1%FA00%A1%FB%A1%FA99%A1%FB%A1%FA%A1%FB%A1%FA99%A1%FB%A1%FA99%A1%FB%A1%FA99%A1%FB%A1%FA99%A1%FB%A1%FA3%A1%FB%A1%FA99%A1%FB%A1%FA%A1%FB%A1%FA0%A1%FB%A1%FApython%A1%FB%A1%FA2%A1%FB%A1%FA1%7C%21recentSearch2%7E%60000000%A1%FB%A1%FA000000%A1%FB%A1%FA0000%A1%FB%A1%FA00%A1%FB%A1%FA99%A1%FB%A1%FA%A1%FB%A1%FA99%A1%FB%A1%FA99%A1%FB%A1%FA99%A1%FB%A1%FA99%A1%FB%A1%FA2%A1%FB%A1%FA99%A1%FB%A1%FA%A1%FB%A1%FA0%A1%FB%A1%FApython%A1%FB%A1%FA2%A1%FB%A1%FA1%7C%21recentSearch3%7E%60000000%A1%FB%A1%FA000000%A1%FB%A1%FA0000%A1%FB%A1%FA00%A1%FB%A1%FA99%A1%FB%A1%FA%A1%FB%A1%FA99%A1%FB%A1%FA99%A1%FB%A1%FA99%A1%FB%A1%FA99%A1%FB%A1%FA0%A1%FB%A1%FA99%A1%FB%A1%FA%A1%FB%A1%FA0%A1%FB%A1%FApython%A1%FB%A1%FA2%A1%FB%A1%FA1%7C%21recentSearch4%7E%60000000%A1%FB%A1%FA000000%A1%FB%A1%FA0000%A1%FB%A1%FA00%A1%FB%A1%FA99%A1%FB%A1%FA%A1%FB%A1%FA99%A1%FB%A1%FA99%A1%FB%A1%FA99%A1%FB%A1%FA99%A1%FB%A1%FA1%A1%FB%A1%FA99%A1%FB%A1%FA%A1%FB%A1%FA0%A1%FB%A1%FApython%A1%FB%A1%FA2%A1%FB%A1%FA1%7C%21; acw_sc__v3=658bb2c2422de30737c5e74161b66e8e19b66b1e; JSESSIONID=6A5F745D919D01FB9789C8F6C8D7B70D; ssxmod_itna=eqUhqGxjEDOiGHD8K044Qw4Wwerni9G9D0o8DGXhrDZDiqAPGhDC43FSeSEOqEehWV07E2EWezmbh4Dg0WRIWYARq4GLDmKDy0nDboYD4fKGwD0eG+DD4DWDmeHDnxAQDjxGP9R6sy=Dbxi3jxiaDGeDe2IODY5DhxDCXAPDwx0CjE0qXhDDBhiA+BWxeIAF=FHpuhr+qQDkD7ypDlcKn+DkrFM6YjH+6/fGE7KDXaQDv1H1l2apDBRkZhvGlYr3=YxerCeoLG2DpBm58A19YYhxbYr9lWb4Yi34=AGPkkN4DDa4al3N4D==; ssxmod_itna2=eqUhqGxjEDOiGHD8K044Qw4Wwerni9G9D0xxA=nK+KD/lmDFr4Yvg+RxPHGFKmhiFosDPbA7iO5b3nWTO79BLhbmVjbaorj45YxSawRKQ6Mb65c4l8acvg4m=Wz01gP1NyAP3W3KH0ioo9G5x2R06COQm9qE2b7rpKBPliRRMYdfxReY00f3UeCwlDbhbpE32b=XfeQt=gxN+0Lh3cmF=XmaOc6Tnf4Y+ff3zC1YH4KOCmhvOWPIjWIYbakKcfFI8CgWvCEIjDH6bmxdmD5L6PWYzYAlf9/8OI+WZitkmF5BRvL3upW=Q4GESPMrqqnO3RroddRk7l384hYSMrOOQbDQMODDbtYTOanWxRHdWOkkQliGi4xqeQBxwVfxCbwTENqExcDPD7QPGh5jYgW4HcDC04tpDRenAQng2r9mh=133aIPgm=i3=BtjtpxDeLzaPBU74Iw9+OYpOBhNlupjnubiwS54itkBU=+G24eQYH8Ww09DWSeQiUtYv/beURnxThWhxeDGcDG7LmbbrDD',
                       'From-Domain': '51job_web', 'Host': 'we.51job.com',
                       'Referer': 'https://we.51job.com/pc/search?keyword=python&searchType=2&sortType=0&metro=',
                       'Sec-Fetch-Dest': 'empty-', 'Sec-Fetch-Mode': 'cors', 'Sec-Fetch-Site': 'same-origin',
                       'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 Edg/120.0.0.0',
                       'account-id': '', 'partner': '',
                       'property': '%7B%22partner%22%3A%22%22%2C%22webId%22%3A2%2C%22fromdomain%22%3A%2251job_web%22%2C%22frompageUrl%22%3A%22https%3A%2F%2Fwe.51job.com%2F%22%2C%22pageUrl%22%3A%22https%3A%2F%2Fwe.51job.com%2Fpc%2Fsearch%3Fkeyword%3Dpython%26searchType%3D2%26sortType%3D0%26metro%3D%22%2C%22identityType%22%3A%22%22%2C%22userType%22%3A%22%22%2C%22isLogin%22%3A%22%E5%90%A6%22%2C%22accountid%22%3A%22%22%2C%22keywordType%22%3A%22%22%7D',
                       'sec-ch-ua': '"Not_A Brand";v="8", "Chromium";v="120", "Microsoft Edge";v="120"',
                       'sec-ch-ua-mobile': '?0', 'sec-ch-ua-platform': '"Windows"',
                       'sign': '61b17616ad021669018a043e81875764a8779dac359b373ddae65eeadf6cb0e4', 'user-token': '',
                       'uuid': 'bed24704cea43240eacb73101cd81594'}
            response = requests.get(url, headers=headers)
            informathion = json.loads(response.content.decode("UTF-8"))
            job = informathion.get("resultbody", {}).get("job", {}).get("items", [])
            job_keys = ['jobName', 'jobHref', 'termStr', 'jobTagsForOrder', 'companyTypeString', 'companySizeString',
                        'fullCompanyName', "jobAreaString", 'provideSalaryString', 'workYearString', 'degreeString',
                        'jobAreaLevelDetail']
            job1_keys = ['工作名称', '工作链接', '工作性质', '员工要求与福利', '企业性质', '企业规模', '企业全称',
                         '工作地点', '薪资', '工作经验要求', '学历要求', "工作省份"]
            for j in job:
                job_dict = {}
                for key, mkey in zip(job_keys, job1_keys):
                    if key in j:
                        if key == "jobAreaLevelDetail":
                            job_dict[mkey] = j[key]["provinceString"]
                        else:
                            job_dict[mkey] = j[key]
                job_list.append(job_dict)
        print(len(job_list))
        with open("JSON/近一个月python语言相关岗位信息采集.json", "w", encoding="UTF-8") as f:
            json.dump(job_list, f, indent=4, ensure_ascii=False)
            f.flush()
    def offer_data_change(self):
        with open("JSON/近一个月python语言相关岗位信息采集.json", "r", encoding="UTF-8") as f:
            offer_list=json.load(f)
        pa1=r'^(?:\d+(?:\.\d*)?|\.\d+)-(?:\d+(?:\.\d*)?|\.\d+)(?:千|万)?$'
        pa2=r'^(?:\d+(?:\.\d*)?|\.\d+)千-(?:\d+(?:\.\d*)?|\.\d+)(?:千|万)?$'
        for offer in offer_list:
            money_dict={}
            if re.search(pa1,offer["薪资"]) is not  None:
                if  offer["薪资"].count("千"):
                    money_dict["月最低薪资"]=int(float(offer["薪资"].split("-")[0])*10**3)
                    money_dict['月最高薪资']=int(float(offer["薪资"].split("-")[1].replace("千",""))*10**3)
                    money_dict['月薪资平均数']=(money_dict["月最低薪资"]+money_dict['月最高薪资'])/2
                    offer["薪资"]=money_dict
                elif  offer["薪资"].count("万"):
                    money_dict["月最低薪资"]=int(float(offer["薪资"].split("-")[0])*10**4)
                    money_dict['月最高薪资']=int(float(offer["薪资"].split("-")[1].replace("万",""))*10**4)
                    money_dict['月薪资平均数']=(money_dict["月最低薪资"]+money_dict['月最高薪资'])/2
                    offer["薪资"]=money_dict
            elif re.search(pa2,offer["薪资"]) is not None:
                money_dict["月最低薪资"]=int(float(offer["薪资"].split("-")[0].replace("千",""))*10**3)
                money_dict['月最高薪资']=int(float(offer["薪资"].split("-")[1].replace("万",""))*10**4)
                money_dict['月薪资平均数']=( money_dict["月最低薪资"]+money_dict['月最高薪资'])/2
                offer["薪资"]=money_dict
            elif offer["薪资"].count("薪"):
                if re.search(r'(?:\d+(?:\.\d*)?|\.\d+)-(?:\d+(?:\.\d*)?|\.\d+)(?:千|万)?',offer["薪资"]) is not  None:
                    if  offer["薪资"].count("千"):
                        money_dict["月最低薪资"]=int(float(offer["薪资"].split("-")[0])*10**3)
                        money_dict['月最高薪资']=int(float(offer["薪资"].split("-")[1].split("·")[0].replace("千",""))*10**3)
                        money_dict['月薪资平均数']=(money_dict["月最低薪资"]+money_dict['月最高薪资'])/2
                        money_dict["额外薪水"]=offer["薪资"].split("-")[1].split("·")[1]
                        offer["薪资"]=money_dict
                    elif  offer["薪资"].count("万"):
                        money_dict["月最低薪资"]=int(float(offer["薪资"].split("-")[0])*10**4)
                        money_dict['月最高薪资']=int(float(offer["薪资"].split("-")[1].split("·")[0].replace("万",""))*10**4)
                        money_dict['月薪资平均数']=(money_dict["月最低薪资"]+money_dict['月最高薪资'])/2
                        money_dict["额外薪水"]=offer["薪资"].split("-")[1].split("·")[1]
                        offer["薪资"]=money_dict
                elif re.search(r'(?:\d+(?:\.\d*)?|\.\d+)千-(?:\d+(?:\.\d*)?|\.\d+)(?:千|万)',offer["薪资"]) is not None:
                    money_dict["月最低薪资"]=int(float(offer["薪资"].split("-")[0].replace("千",""))*10**3)
                    money_dict['月最高薪资']=int(float(offer["薪资"].split("-")[1].split("·")[0].replace("万",""))*10**4)
                    money_dict['月薪资平均数']=(money_dict["月最低薪资"]+money_dict['月最高薪资'])/2
                    money_dict["额外薪水"]=offer["薪资"].split("-")[1].split("·")[1]
                    offer["薪资"]=money_dict
            elif str(type(offer["薪资"])).count("str"):
                if offer["薪资"].count("万/年"):
                    money_dict["月最低薪资"]= round(((float(offer["薪资"].replace("万/年","").split("-")[0])*10**4)/12),2)
                    money_dict['月最高薪资']=round((float(offer["薪资"].replace("万/年","").split("-")[1])*10**4)/12,2)
                    money_dict['月薪资平均数']=( money_dict["月最低薪资"]+money_dict['月最高薪资'])/2
                    offer["薪资"]=money_dict
                elif offer["薪资"].count("元/天"):
                    money_dict["月估算薪资"]=float(offer["薪资"].replace("元/天",""))*30.5
                    money_dict["备注"]="兼职，日薪，这里做了连续干一个月的估算"
                    offer["薪资"]=money_dict
                elif offer["薪资"].count("千/天"):
                    money_dict["月估算薪资"]=float(offer["薪资"].replace("千/天",""))*1000*30.5
                    money_dict["备注"]="兼职，日薪，这里做了连续干一个月的估算"
                    offer["薪资"]=money_dict
            elif offer["薪资"]=="":
                offer_list.remove(offer)
        with open("JSON/近一个月python语言相关岗位信息采集(薪资粗清洗版).json", "w", encoding="UTF-8") as f:
            json.dump(offer_list,f,indent=4,ensure_ascii=False)
            f.flush()
    def offer_salary_statistics(self):
        key_name_list=["月最低薪资","月最高薪资", "月薪资平均数"]
        with open("JSON/近一个月python语言相关岗位信息采集(薪资粗清洗版).json", "r", encoding="UTF-8") as f:
            offer_list=json.load(f)
        for key_name in key_name_list:
            offer_salary_dict = {f"{key_name}少于等于4000元的offer数量": 0,
                                 f"{key_name}是4000到8000之间(包含8000)元的offer数量": 0,
                                 f"{key_name}是8000到15000之间(包含15000)元的offer数量": 0,
                                 f"{key_name}是15000至20000之间(包含20000)元的offer数量": 0,
                                 f"{key_name}大于20000元的offer数量": 0}
            for offer_min_salary in offer_list:
                if f"{key_name}" in offer_min_salary["薪资"]:
                    if offer_min_salary["薪资"][f"{key_name}"] <= 4000:
                        offer_salary_dict[f"{key_name}少于等于4000元的offer数量"]
                    elif 4000 < offer_min_salary["薪资"][f"{key_name}"] <= 8000:
                        offer_salary_dict[f"{key_name}是4000到8000之间(包含8000)元的offer数量"]+=1
                    elif 8000 < offer_min_salary["薪资"][f"{key_name}"] <= 15000:
                        offer_salary_dict[f"{key_name}是8000到15000之间(包含15000)元的offer数量"]+=1
                    elif 15000 < offer_min_salary["薪资"][f"{key_name}"] <= 20000:
                        offer_salary_dict[  f"{key_name}是15000至20000之间(包含20000)元的offer数量"]+=1
                    else:
                        offer_salary_dict[f"{key_name}大于20000元的offer数量"]+=1
                if key_name=="月最高薪资":
                    if "月估算工资" in offer_min_salary["薪资"]:
                        if offer_min_salary["薪资"]["月估算工资"] <10000:
                            offer_salary_dict[f"{key_name}是4000到8000之间(包含8000)元的offer数量"]+=1
                        else:
                            offer_salary_dict[f"{key_name}大于20000元的offer数量"]+=1
            with open(f"{key_name}情况offer数量数据.json", "w", encoding="UTF-8") as f:
                json.dump(offer_salary_dict, f, indent=4, ensure_ascii=False)
    def draw_benifit_pie(self):
        with open("JSON/员工福利统计数据.json", "r", encoding="UTF-8") as f:
            benifit_dict=json.load(f)
        tickt=list(benifit_dict.keys())
        tickt.append("无保险offer")
        values=list(benifit_dict.values())
        values.append(1040-(values[0]+values[1]))
        plt.figure(figsize=(8, 8))
        plt.pie(values, labels=tickt, autopct='%1.1f%%', explode=[0, 0.1, 0.1])
        plt.title('员工保险福利占比情况')
        plt.legend()
        plt.savefig('picture/员工保险福利占比情况.jpg')
        plt.show()
    def create_province_map(self):
        data = {
            "广东省": 304,
            "河北省": 2,
            "湖南省": 14,
            "福建省": 7,
            "河南省": 4,
            "陕西省": 10,
            "上海市": 218,
            "黑龙江省": 7,
            "江苏省": 145,
            "辽宁省": 22,
            "浙江省": 61,
            "天津市": 8,
            "北京市": 102,
            "安徽省": 12,
            "湖北省": 43,
            "四川省": 45,
            "重庆市": 16,
            "广西壮族自治区": 2,
            "山东省": 10,
            "江西省": 5
        }
        province= list(data.items())
        map_chart = (
            Map()
            .add("各省提供offer的企业数量大小", province, maptype="china", is_roam=True)
            .set_global_opts(
                title_opts=opts.TitleOpts(title="各省市offer提供的企业数量热度图"),
                visualmap_opts=opts.VisualMapOpts(max_=max(data.values()),  is_piecewise=True),
            )
            .set_series_opts(label_opts=opts.LabelOpts(is_show=True, color="black"))
        )
        file_name = "picture/各省市offer提供的企业数量热度图.html"
        map_chart.render(file_name)
        with open(file_name, 'r', encoding='utf-8') as f:
            soup = BeautifulSoup(f.read(), 'html.parser')
        map_container = soup.find('div', {'class':"chart-container"})
        map_container['style'] = 'width:100%;height:600px;'
        with open(file_name, 'w', encoding='utf-8') as f:
            f.write(str(soup))
        webbrowser.open(file_name)
    #徐诗睿编写部分
    def __read_json_to_dataframe(self,file_path):
        with open(file_path, 'r', encoding='utf-8') as file:
            data = json.load(file)
            df = pd.DataFrame(data.items(), columns=['Category', 'Value'])
        return df
    def plot_bar_chart(self):
        df = self.__read_json_to_dataframe("JSON/企业规模统计数据.json")
        plt.figure(figsize=(10, 6))
        plt.bar(df['Category'], df['Value'])
        plt.xlabel('人数范围')
        plt.ylabel('提供offer的企业数量')
        plt.title('企业规模统计数据柱状图')
        plt.savefig('picture/企业规模统计数据柱状图.jpg')
        plt.show()
    def plot_pie_chart(self):
        df = self.__read_json_to_dataframe("JSON/企业性质统计数据.json")
        explode = [0.2 if cat == "政府机关" else 0.3 if cat == "创业公司" else 0 for cat in df['Category']]  # 设置分离度
        plt.figure(figsize=(8, 8))
        plt.pie(df['Value'], labels=df['Category'], autopct='%1.1f%%', explode=explode)
        plt.title('企业性质统计饼图')
        plt.legend(loc=2)
        plt.savefig('picture/企业性质统计饼图.jpg')
        plt.show()
    def plot_line_chart(self):
        df = self.__read_json_to_dataframe('JSON/工作经验要求统计数据.json')
        plt.figure(figsize=(10, 6))
        plt.plot(df['Category'], df['Value'],marker='o', color='red')
        plt.xlabel('工作经验要求')
        plt.ylabel('提供的offer的企业数量')
        plt.title('工作经验要求统计数据折线图')
        plt.xticks(rotation=45)
        plt.savefig('picture/工作经验要求统计数据折线图.jpg')
        plt.show()
    #刘媛媛编写部分
    def data_handle(self):
        province_list=['广东省', '河北省', '湖南省', '福建省', '河南省', '陕西省', '上海', '黑龙江省', '江苏省', '辽宁省', '深圳', '浙江省', '天津', '北京', '安徽省', '湖北省', '四川省', '重庆', '广西', '山东省', '江西省']
        enterprise_list=['合资', '民营', '国企', '政府机关', '创业公司', '外资（非欧美）', '外资（欧美）', '事业单位', '非营利组织', '已上市']
        greedy_list=['本科', '硕士', '大专', '高中']
        enterprise_size_list=['50-150人', '少于50人', '10000人以上', '500-1000人', '5000-10000人', '150-500人', '1000-5000人']
        job_performance_rewards=['2年', '3年及以上', '2年及以上', '1-3年', '无需经验', '1-2年', '5-7年', '1年', '1年及以上', '4年及以上', '10年及以上', '1-4年', '2-10年', '5年及以上', '8-9年', '2-4年', '5-9年', '3-4年', '3-5年']
        temp_list=[province_list, enterprise_list,greedy_list,enterprise_size_list,job_performance_rewards]
        name_list=["工作省份","企业性质","学历要求","企业规模","工作经验要求"]
        for data_list,name in zip(temp_list,name_list):
            self.__offer_handle(data_list,name)
    def __offer_handle(self,data_list,name):
        with open("JSON/近一个月python语言相关岗位信息采集.json", "r", encoding="UTF-8") as f:
            offer_list=json.load(f)
        # offer_set=set()
        offer_dict={key:0 for key in data_list}
        for offer in offer_list:
                if name in offer.keys():
                    for data in data_list:
                        if offer[name]==data:
                            offer_dict[data]=offer_dict[data]+1
        if name=="工作省份":
                offer_dict["广东省"]=offer_dict["广东省"]+offer_dict["深圳"]
                shen_zhen_offer=offer_dict.pop("深圳","default")
        with open(f"{name}统计数据.json","w",encoding="UTF-8") as f:
            json.dump(offer_dict,f,indent=4,ensure_ascii=False)
            f.flush()
    def process_data(self):
        with open("JSON/近一个月python语言相关岗位信息采集.json", "r", encoding="UTF-8") as f:
            offer_list = json.load(f)
        result_dict = {key: 0 for key in ["五险一金","六险一金"]}
        for offer in offer_list:
            if "员工要求与福利" in offer.keys():
                nested_data = offer["员工要求与福利"]
                if any(data in nested_data for data in ["五险一金","六险一金"]):
                    for data in ["五险一金","六险一金"]:
                        if data in nested_data:
                            result_dict[data] += 1
        with open("JSON/员工福利统计数据.json", "w", encoding="UTF-8") as f:
            json.dump(result_dict, f, indent=4, ensure_ascii=False)
    def work_year_requirement_wash(self):
        with open('JSON/近一个月python语言相关岗位信息采集(薪资粗清洗版).json', 'r', encoding='utf-8') as file:
            json_data = json.load(file)
            # 统计工作经验要求次数
        pa1='^[1-9]?[0-9]?-[1-9]?[0-9]?年$'
        pa2='[3-9][0-9]*年'
        for job in json_data:
            if '工作经验要求' in job:
                experience_requirement_dict={}
                experience_requirement = job['工作经验要求']
                if re.search(pa1,experience_requirement):
                    experience_requirement_dict["最低工作经验要求年限"]=int(experience_requirement.split('-')[0])
                    experience_requirement_dict['最高工作经验要求年限']=int(experience_requirement.split('-')[1].replace("年",""))
                    experience_requirement_dict['中值年限']=(experience_requirement_dict["最低工作经验要求年限"]+experience_requirement_dict['最高工作经验要求年限'])/2
                    job["工作经验要求"]=experience_requirement_dict
                elif re.search(pa2,experience_requirement):
                    experience_requirement_dict["最低工作经验要求年限"]=int(experience_requirement[0:1])
                    job['工作经验要求']=experience_requirement_dict
            with open("JSON/近一个月python语言相关岗位信息采集(薪资粗清洗版).json", "w", encoding="UTF-8") as f:
                    json.dump(json_data,f,indent=4,ensure_ascii=False)
                    f.flush()
    def work_year_to_json(self):
        with open("JSON/近一个月python语言相关岗位信息采集(薪资粗清洗版).json", "r", encoding="UTF-8") as f:
            offer_list=json.load(f)
        experience_count = {'无需经验': 0, '1年':0,'2年':0,'3年及以上': 0, '3年及以上': 0, '5年及以上': 0, '10年及以上': 0}
        for offer in offer_list:
            if '中值年限' in offer["工作经验要求"]:
                if 3<=offer['工作经验要求']['中值年限']<5:
                    experience_count['3年及以上']+=1
                elif 5<=offer['工作经验要求']['中值年限']<10:
                    experience_count['5年及以上']+=1
                elif 10<=offer['工作经验要求']['中值年限']:
                    experience_count['10年及以上']+=1
            elif len(offer)==1 and '最低工作经验要求年限' in offer['工作经验要求']:
                if 3<=offer['工作经验要求']['最低工作经验要求年限']<5:
                    experience_count['3年及以上']+=1
                elif 5<=offer['工作经验要求']['最低工作经验要求年限']<10:
                    experience_count['5年及以上']+=1
                elif 10<=offer['工作经验要求']['最低工作经验要求年限']:
                    experience_count['10年及以上']+=1
            elif str(type(offer['工作经验要求'])).count("str"):
                if offer['工作经验要求'].count('1年'):
                        experience_count["1年"]+=1
                elif offer['工作经验要求'].count('2年'):
                        experience_count['2年']+=1
                elif offer['工作经验要求'].count('10年及以上'):
                    experience_count['10年及以上']+=1
                else:
                    experience_count['无需经验']+=1
        with open("JSON/工作经验统计数据.json","w",encoding="UTF-8") as f:
            json.dump(experience_count,f,indent=4,ensure_ascii=False)
            f.flush()
    #王见辉编写部分
    def ploy_gzsf(self):
        with open("JSON/工作经验统计数据.json", 'r', encoding='utf-8') as file:
            data = json.load(file)
        # 省份和数值
        provinces = list(data.keys())
        values = list(data.values())
        explode = [0,0,0.1,0,0.2,0]
        plt.figure(figsize=(10, 8))
        wedges, texts, autotexts =plt.pie(values, labels=provinces, autopct='%1.1f%%', explode=explode)
        plt.title('工作经验占比')
        plt.legend(loc="upper right")
        plt.savefig("picture/工作经验统计图.jpg")
        plt.show()
    def plot_xlyq(self):
        with open("JSON/学历要求统计数据.json", 'r', encoding='utf-8') as file:
            data = json.load(file)
        # 提取标签对应的数量
        labels = list(data.keys())
        values = list(data.values())
        colors = ['#BBFFFF', '#FFDAB9', '#00FF7F', 'red']
        explode = [0, 0, 0, 0.1]
        plt.pie(values, labels=labels, autopct='%1.1f%%', colors=colors, explode=explode, startangle=90)
        plt.title("offer对于最低学历要求占比图")
        plt.savefig("picture/最低学历要求统计图.jpg")
        plt.show()
    def plot_xz(self):
        with open('JSON/月最低薪资情况offer数量数据.json', 'r', encoding='utf-8') as file1:
            data1 = json.load(file1)
        with open('JSON/月最高薪资情况offer数量数据.json', 'r', encoding='utf-8') as file2:
            data2 = json.load(file2)
        with open('JSON/月薪资平均数情况offer数量数据.json', 'r', encoding='utf-8') as file3:
            data3 = json.load(file3)
        labels = ['<4k', '4k~8k', '8k~15k', '15k~20k', '>20k']
        values1 = list(data1.values())
        values2 = list(data2.values())
        values3 = list(data3.values())
        x = range(len(labels))
        width = 0.2
        plt.bar(x, values1, width=width, label='月最低薪资', color='#FFE4E1')
        plt.bar([i + width for i in x], values2, width=width, label='月最高薪资', color='#FFA500')
        plt.bar([i + 2 * width for i in x], values3, width=width, label='月薪资平均数', color='#90EE90')
        plt.xlabel('薪资范围')
        plt.ylabel('Offer数量')
        plt.title('不同薪资范围的Offer数量')
        plt.grid()
        plt.xticks([i + width for i in x], labels)
        for i, value in enumerate(values1):
            plt.text(i, value + 10, str(value), ha='center')
        for i, value in enumerate(values2):
            plt.text(i + width, value + 10, str(value), ha='center')
        for i, value in enumerate(values3):
            plt.text(i + width * 2, value + 10, str(value), ha='center')
        plt.legend()
        plt.savefig('picture/不同薪资范围的Offer数量')
        plt.show()
    def plot_average_salary(self):
        with open('JSON/近一个月python语言相关岗位信息采集(薪资粗清洗版).json', 'r', encoding='utf-8') as file:
            data = json.load(file)
        average_salaries = []
        x = []
        for i, item in enumerate(data, start=1):
            if '薪资' in item and '月薪资平均数' in item['薪资']:
                average_salaries.append(item['薪资']['月薪资平均数'])
                x.append(i)
        average_salary = sum(average_salaries) / len(average_salaries)
        plt.axhline(average_salary, color='r', linestyle='--', label=f'平均工资:{average_salary:.2f}元')
        plt.scatter(x, average_salaries, color='lightgreen',s=10)
        plt.xlabel('公司序号')
        plt.ylabel('月薪资平均数')
        plt.title('月薪资平均数散点分布')
        plt.legend()
        plt.savefig('picture/月薪资平均数散点分布图.jpg')
        plt.show()

if __name__ == '__main__':
    position=Position()